//
//  GroupOrderConfirmCtr.swift
//  eemall
//
//  Created by zhuxietong on 2018/12/25.
//  Copyright © 2018 tianrun. All rights reserved.
//
import UIKit
import Eelay
import soapp
// import mosdks

enum GroupOrderType  {
    case single(option:[String:Any])
    case join(info:[String:Any])
    case start(info:[String:Any])
    
    var submitName:String{
        get{
            switch self {
            case .join(info: _):
                return "参与团购".loc
            case .start(info: _):
                return "发起拼团".loc
            default:
                return "提交订单".loc
            }
        }
    }
    
    func confirmParams()->[String:Any]
    {
        var params = [String:Any]()
        switch self {
        case .single(option: let info):
            let obj = info.mutable_dictionary
            params["type"] = "single"
            params["options_id"] = obj["optionid",""]
            params["goodsid"] = obj["goodsid",""]
        case .join(info: let info):
            let obj = info.mutable_dictionary
            params["type"] = "groups"
            params["options_id"] = obj["optionid",""]
            params["goodsid"] = obj["goodsid",""]
            params["teamid"] = obj["teamid",""]
            let gid = obj["group_id",""]
            if gid.len > 0
            {
                params["ladder_id"] = gid
            }
        case .start(info: let info):
            let obj = info.mutable_dictionary
            params["type"] = "groups"
            params["heads"] = "1"
            params["options_id"] = obj["optionid",""]
            params["goodsid"] = obj["goodsid",""]
            let gid = obj["group_id",""]
            if gid.len > 0
            {
                params["ladder_id"] = gid
            }
        }
        return params
    }
}

open class GroupOrderConfirmCtr: SCOrderSubmitCtr {
    
    var groupType:GroupOrderType = .single(option: [String:Any]())
    
    override open var sections:TP.section{
        get{
            let spec = GoodsSpec(goods: mo.detail)
            var address = spec.uisection_address
            switch groupType {
            case .single:
                break
            default:
                address.remove(at: 0)
                address.insert(["cellID":"groupNotice"], at: 0)
            }
            
            let sec:TP.section = [
                address,
                [],
                //                [
                //                    ["id":"line30"],
                //                ],
//                [
//                    [
//                        "title":"选择支付方式".loc,
//                        "cellID":"payMethod",
//                        FK.fields:[
//                            [
//                                FK.value:PayMethod.defaultMethod.rawValue,
//                                FK.options:PayMethod.payOptions,
//                                FK.field:StrField(id: "paytype", defaultV: nil, need: false, hiden: false, rule:
//                                    JoRule(reg: "^[\\s\\S]{0,200}$", nil_msg: "选择支付方式".loc, err_msg: "选择支付方式".loc))
//                            ]
//                        ],
//                        ],
//                    ],
                    spec.uisection_verification_person,
                ]
            return sec
        }
    }
    
    
    open override var selector: TP.selector{
        get{
            var s = super.selector
            s["cellID<goods>"] = GroupGoodsCell.self
            s["cellID<groupNotice>"] = GroupNoticeCell.self
            return s
        }
    }

    open override func viewDidLoad() {
        super.viewDidLoad()
        title = groupType.submitName
        

    }
    
    
    /*
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    override open func mo_request_send() {
        
        let params = groupType.confirmParams()
        loadingV.loading()
        weak var wself = self
        JoTask().post._surl(.团购提交确认).params(params).json_handle { (status, msg, obj, resp) in
            wself?.loadingV.dismiss()
            if status.isSuccess{
                if let dict = obj as? NSMutableDictionary{
                    wself?.mo.detail = dict
                    return
                }
            }
            wself?.mo_request_alert(msg: msg, title: "", bt_title: "")
        }.run()
    }
    
    lazy var hud:HUD = {
        return HUD(at:self.view)
    }()
    
    override func submitSend(params: [String : Any]) {
        let remarkObj = params.mutable_dictionary["remark",""]
        let remark = remarkObj.swift_array?.mutable_array["0.remark",""] ?? ""
        
        var ps = params
        ps["remark"] = remark
//        ps["goodsid"] = mo.detail["list.0.goods.goodsid",""]
//        ps["options_id"] = mo.detail["list.0.goods.optionid",""]
        ps["type"] = "groups"
        ps = ps + groupType.confirmParams()
        
        ps.removeValue(forKey: "fromcart")
        ps.removeValue(forKey: "goods")
        
        let pay_method = PayMethod.method(with: params.mutable_dictionary["paytype",""])
        weak var wself = self
            hud.show().mode(.indeterminate)

        JoTask().post.params(ps)._surl(.团购提交).json_handle { (status, msg, obj, resp) in
            wself?.hud.hide(animated: true)
            
//            if status.isSuccess{
//                guard let _ = wself else {return}
//                __post(notify: Goods.Notice.groupOrderChange)
//
//                if let dict = obj as? NSMutableDictionary{
//
//                    DoPay.pay(pay_method.rawValue, pay_id: dict["product_id",""], task_type: "PayTaskType.goods", dict, finish_block: { (result, task_type, pay_id) in
//
//                        switch result{
//                        case .ok:
//                            wself?.showGroupDetail(info:dict)
////                            GroupOrderConfirmCtr.showGroupPaySuccessResult(order: dict)
//                        case .canle:
//                            break
//                        case .failed(_,_):
//                            "支付失败".alert()
////                            wself?.showGroupDetail(info: dict)
////                            GroupOrderConfirmCtr.showGroupPayFailedResult(order: dict)
//                        }
//                    })
////                    wself?.showGroupDetail(info: dict)
//                    return
//                }
//            }
            
            if status.isSuccess{
                            guard let ws = wself else {return}
                __post(notify: Goods.Notice.groupOrderChange)

                            switch ws.buyType{
                            case .oneGoods(_):
                                __post(notify: Goods.Notice.goodsOrderChange)
                            case .cartGoods(_):
                                __post(notify: Goods.Notice.goodsOrderChange)
                                __post(notify: Goods.Notice.goodsCartChage)
                            }
                            
                            if let order = obj as? NSMutableDictionary{
                                let ctr = PayController()
                                ctr.task = .groups

//                                switch ws.buyType {
//                                case .cartGoods:
//                                    ctr.from = "cart"
//                                case .oneGoods:
//                                    ctr.from = "goods"
//                                }
                                ctr.mo.model = order
            //                    wself?.navigationController?.pushViewController(ctr, animated: true)
                                
                                ctr.presentType = .navRootPresent
                                SCOrderSubmitCtr.orderDetailCtr = nil
                                let nav = RootNavigationController(rootViewController: ctr)
                                weak var wself = self
                                self.navigationController?.present(nav, animated: true, completion: {
                                    wself?.popController(1)
                                })
                                return
                            }
            }
            msg.alert()
            }.run()
        
    }
}


extension GroupOrderConfirmCtr{
    
    class GroupNoticeCell: JoTableCell {
        let titleL = UILabel()
        override func addLayoutRules() {
            contentView.eelay = [
                [titleL,[ee.T.L.B.R,[12,AppTheme.edge,-8,-AppTheme.edge]]]
            ]
            titleL.numberOfLines = 0
            titleL.attributedText = "提示：未在有效时间内邀请足够订单将取消拼团，系统会自动退款".loc.ui.font13.lineSpace(5).cl_333.astring
            titleL.lineBreakMode = .byTruncatingTail
            contentView.backgroundColor = UIColor(shex: "#FEC6B2")
        }
    }
    class GroupGoodsCell: GoodsCell {
        override func mo_model_reload() {
            imgV.img_url = mo.model["thumb",""]
            titleL.tagStr = ""
            titleL.text = mo.model["title",""]
            tagsL.text = mo.model["optiontitle",""]
            priceL.attributedText = "¥ ".ui.font11.color(color: ___shop.second).astring +  mo.model[float:"marketprice",0].price_display.ui.font13.color(color: ___shop.second).astring
            numL.attributedText = "X ".ui.font10.cl_999.astring + mo.model["total","1"].ui.font13.cl_666.astring
        }
    }
}

extension GroupOrderConfirmCtr{
    
//     static func showGroupPaySuccessResult(order:NSMutableDictionary) {
//        co_delay(delay: 0.3) {
//            __post(notify: Goods.Notice.groupOrderChange)
//        }
//
//        let ctr = 订单支付Ctr()
//        ctr.mo.model = order
//        ctr.payStatus = .success
//        ctr.presentType = .defaultPush
//
//        GroupOrderConfirmCtr.groupDetailCtr?.navigationController?.pushViewController(ctr, animated: true)
//        GroupOrderConfirmCtr.groupDetailCtr = nil
//    }
//
//    static func showGroupPayFailedResult(order:NSMutableDictionary) {
//
//        let ctr = 订单支付Ctr()
//        ctr.mo.model = order
//        ctr.payStatus = .failed
//        ctr.presentType = .defaultPush
//        SCOrderSubmitCtr.orderDetailCtr?.navigationController?.pushViewController(ctr, animated: true)
//        SCOrderSubmitCtr.orderDetailCtr = nil
//    }
    
    func showGroupDetail(info:NSMutableDictionary) {
     
        let product_id = info["product_id","0"]
        if product_id != "0"
        {
            let ctr = GroupInfoCtr()
            ctr.mo.model = ["teamid":product_id].mutable_dictionary
            ctr.presentType = .navRootPresent
            let nav = RootNavigationController(rootViewController: ctr)
            weak var wself = self
            self.navigationController?.present(nav, animated: false, completion: {
                wself?.popController(1)
            })
        }
        else{
            "未获取到团购ID".alert()
        }
     
    }
    
}
